# -*- coding: utf-8 -*-
"""
Created on Tue Mar  4 10:50:52 2025

@author: 18523
"""
import base64
import requests
import cv2 
import time 
import numpy as np
import json
import httpx
import os
from config import APIConfig, RAGConfig


def frames_to_base64(frames, fps, timestamps):
    try:
        print(f"开始处理视频帧并转换为base64...")
        print(f"处理 {len(frames)} 帧，FPS: {fps}")
        
        # 确保video_warning目录存在
        os.makedirs('./video_warning', exist_ok=True)
        
        # 获取第一帧的尺寸
        if not frames or len(frames) == 0:
            print("错误: 没有帧可以处理")
            return ""
        
        # 检查帧的数据类型和形状
        first_frame = frames[0]
        print(f"帧类型: {first_frame.dtype}, 形状: {first_frame.shape}")
        
        # 确保帧是正确的数据类型
        processed_frames = []
        for frame in frames:
            if frame.dtype != np.uint8:
                frame = frame.astype(np.uint8)
            if len(frame.shape) == 2:
                # 如果帧是灰度的，转换为BGR
                frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
            processed_frames.append(frame)
        
        width = processed_frames[0].shape[1]
        height = processed_frames[0].shape[0]
        print(f"视频尺寸: {width}x{height}")
        
        # 尝试多种编解码器
        codecs_to_try = [
            ('mp4v', './video_warning/output.mp4'),  # MP4
            ('XVID', './video_warning/output.avi'),  # AVI
            ('MJPG', './video_warning/output.avi'),  # Motion JPEG
            ('WMV1', './video_warning/output.wmv')   # Windows Media Video
        ]
        
        video_path = None
        for codec, path in codecs_to_try:
            try:
                print(f"尝试使用编解码器: {codec}")
                fourcc = cv2.VideoWriter_fourcc(*codec)
                video_writer = cv2.VideoWriter(path, fourcc, fps, (width, height))
                
                if video_writer.isOpened():
                    print(f"成功创建视频写入器，使用编解码器: {codec}")
                    # 写入帧
                    for frame in processed_frames:
                        video_writer.write(frame)
                    
                    # 释放资源
                    video_writer.release()
                    video_path = path
                    print(f"视频已成功保存到: {video_path}")
                    break
                else:
                    print(f"无法使用编解码器 {codec} 创建视频写入器")
            except Exception as e:
                print(f"使用编解码器 {codec} 时出错: {e}")
        
        # 检查是否成功创建了视频
        if video_path and os.path.exists(video_path) and os.path.getsize(video_path) > 0:
            print(f"视频文件大小: {os.path.getsize(video_path)} 字节")
            
            # 将视频转换为base64
            try:
                with open(video_path, 'rb') as video_file:
                    video_base64 = base64.b64encode(video_file.read()).decode('utf-8')
                print(f"Base64编码成功，长度: {len(video_base64)}")
                return video_base64
            except Exception as e:
                print(f"Base64编码过程中出错: {e}")
                return ""
        else:
            # 如果所有编解码器都失败，尝试直接保存帧作为图片
            print("所有编解码器都失败，尝试保存第一帧作为图片")
            try:
                image_path = './video_warning/first_frame.jpg'
                cv2.imwrite(image_path, processed_frames[0])
                print(f"已保存第一帧为图片: {image_path}")
                
                # 返回空字符串，表示视频处理失败
                return ""
            except Exception as e:
                print(f"保存图片时出错: {e}")
                return ""
    except Exception as e:
        print(f"视频处理过程中出错: {e}")
        import traceback
        traceback.print_exc()
        return ""



async def video_chat_async(text, frames, timestamps, fps=20):
    try:
        print("开始处理视频帧并转换为base64...")
        video_base64 = frames_to_base64(frames, fps, timestamps)
        
        if not video_base64:
            print("错误: 无法将视频帧转换为base64格式")
            return "无法处理视频内容，请检查视频格式或重新上传。"
        
        # 修复打印base64长度的代码
        print(f"视频base64编码完成，长度: {len(video_base64)}")
        
        url = APIConfig.QWEN_API_URL
        headers = {
            "Content-Type": "application/json",
            "authorization": APIConfig.QWEN_API_KEY
        }
        model = APIConfig.QWEN_MODEL
        
        print(f"准备调用视觉模型API: {model}")
        
        data = {
            "model": model,
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": text},
                        {
                            "type": "video_url",
                            "video_url": {
                                "url": f"data:video/mp4;base64,{video_base64}"
                            }
                        }
                    ]
                }
            ],
            "stop_token_ids": [151645, 151643]
        }
        
        print("发送API请求到通义千问视觉模型...")
        async with httpx.AsyncClient(timeout=httpx.Timeout(APIConfig.REQUEST_TIMEOUT)) as client:
            try:
                response = await client.post(url, headers=headers, json=data)
                print(f"API响应状态码: {response.status_code}")
                
                if response.status_code != 200:
                    print(f"API请求失败: {response.text}")
                    return f"API请求失败，状态码: {response.status_code}，请检查API配置和网络连接。"
                
                response_data = response.json()
                print("成功获取API响应")
                
                if 'choices' not in response_data or not response_data['choices']:
                    print(f"API响应格式错误: {response_data}")
                    return "API响应格式错误，请检查API配置。"
                    
                return response_data['choices'][0]['message']['content']
                
            except httpx.RequestError as e:
                print(f"API请求错误: {e}")
                return f"API请求错误: {str(e)}"
                
            except Exception as e:
                print(f"处理API响应时出错: {e}")
                import traceback
                traceback.print_exc()
                return f"处理API响应时出错: {str(e)}"
    
    except Exception as e:
        print(f"视频处理过程中出错: {e}")
        import traceback
        traceback.print_exc()
        return f"视频处理过程中出错: {str(e)}"


async def chat_request(message, stream=False):
    try:
        print(f"准备调用语言模型API...")
        url = APIConfig.MOONSHOT_API_URL
        model = APIConfig.MOONSHOT_MODEL

        messages = [{"role": "user", "content": message}]
        headers = {
            "Content-Type": "application/json",
            "authorization": APIConfig.MOONSHOT_API_KEY
        }
        data = {
            "messages": messages,
            "model": model,
            "repetition_penalty": APIConfig.REPETITION_PENALTY,
            "temperature": APIConfig.TEMPERATURE,
            "top_p": APIConfig.TOP_P,
            "top_k": APIConfig.TOP_K,
            "stream": stream
        }
        
        print(f"发送API请求到Moonshot语言模型: {model}...")
        async with httpx.AsyncClient(timeout=httpx.Timeout(APIConfig.REQUEST_TIMEOUT)) as client:
            try:
                response = await client.post(url, headers=headers, json=data)
                print(f"API响应状态码: {response.status_code}")
                
                if response.status_code != 200:
                    print(f"API请求失败: {response.text}")
                    return f"API请求失败，状态码: {response.status_code}，请检查API配置和网络连接。"
                
                response_data = response.json()
                print("成功获取API响应")
                
                if 'choices' not in response_data or not response_data['choices']:
                    print(f"API响应格式错误: {response_data}")
                    return "API响应格式错误，请检查API配置。"
                
                return response_data['choices'][0]['message']['content']
                
            except httpx.RequestError as e:
                print(f"API请求错误: {e}")
                return f"API请求错误: {str(e)}"
                
            except Exception as e:
                print(f"处理API响应时出错: {e}")
                import traceback
                traceback.print_exc()
                return f"处理API响应时出错: {str(e)}"
    
    except Exception as e:
        print(f"调用语言模型过程中出错: {e}")
        import traceback
        traceback.print_exc()
        return f"调用语言模型过程中出错: {str(e)}"

def insert_txt(docs,table_name):
    #插入文本，同时向量化
    url = RAGConfig.VECTOR_API_URL
    """docs = [
        "Artificial intelligence was founded as an academic discipline in 1956.",
        "The field of AI research was founded at a workshop held on the campus of Dartmouth College during the summer of 1956."
    ]"""
    data = {
        "docs": docs,
        "table_name": table_name
    }
    response = requests.post(url, json=data)
    return response.json()
